package net.mujiwulian.configs.security;


import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import net.mujiwulian.enums.RedisKey;
import net.mujiwulian.utils.Ip;
import net.mujiwulian.utils.JwtTokenUtil;
import net.mujiwulian.view.UserSimple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author silence
 * @Description: 自定义token验证
 */
@Slf4j
@Component("jwtAuthenticationTokenFilter")
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("本次访问路径--------------" + request.getRequestURI());
        String authHeader = request.getHeader("Authorization");
        String tokenHead = "Bearer:";
        if (authHeader != null && authHeader.startsWith(tokenHead) && SecurityContextHolder.getContext().getAuthentication() == null) {
            String token = authHeader.substring(tokenHead.length());
            //token是否过期
            JwtTokenUtil.CheckResult<Claims> checkResult = jwtTokenUtil.isExpired(token);
            if (checkResult.isSuccess()) {
                Claims claims = checkResult.getData();
                //从请求带的token中获取用户信息
                UserSimple userDetails = (UserSimple) jwtTokenUtil.getUser(claims);
                //获取redis中的token
                String redisToken = redisTemplate.opsForValue().get(RedisKey.TOKEN.value() + userDetails.getUsername());
                //验证本次请求的token的合法性
                JwtTokenUtil.CheckResult<String> validateResult = jwtTokenUtil.validateToken(claims, token, redisToken, Ip.getRealIp(request));
                if (validateResult.isSuccess()) {
                    if (validateResult.getData() != null) {
                        response.setHeader("token", validateResult.getData());
                    }
                    SecurityContextHolder.getContext().setAuthentication(userDetails);
                }
            }
        }
        filterChain.doFilter(request, response);
    }


}
